

import React, { useState ,useEffect} from 'react';
import { Form, Input, Card, Radio, Select,DatePicker,TreeSelect ,Space,Button,Steps,message} from 'antd';
const { Option } = Select;
const { TextArea } = Input;
const { Step } = Steps;
import { PlusOutlined,MinusCircleOutlined, ContactsOutlined } from '@ant-design/icons';
import { history ,useModel} from 'umi';
import styles from '../details/index.less';
import moment from 'moment'
const FormItem = Form.Item;
import { validatorMobile } from '@/utils/utils';

import { addDevice } from '@/services/device';


const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 12 },
};

const formItemLayout = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

let configItem=["commandPort","dataBits","baudRate","stopBits","parity","ipport"];
const CreatDevice:React.FC = (props: any) => {
  const { initialState } = useModel('@@initialState');
  const { dicts } = initialState || {};



 const [formValues,setFormValues] = useState<API.DeviceItem>({useState:0});
  

  const [form] = Form.useForm();
  const [configRow,setConfigRow]= useState<number>(6);
  const [currentStep, setCurrentStep] = useState<number>(0);
  const forward = () => setCurrentStep(currentStep + 1);
  const backward = () => setCurrentStep(currentStep - 1);



  const [protocolTypeList, setProtocolTypeList] = useState<API.DictItem[]>([]);
  const [deviceTypeList, setDeviceTypeList] = useState<API.DeviceTypeItem[]>([]);
  const [driverList, setDriverList] = useState<API.DriverItem[]>([]);
  const [areaTree, setAreaTree] = useState<API.AreaItem[]>([]);
  
  const [btnDisabled, setBtnDisabled] = useState<boolean>(false);
  console.log(btnDisabled)
  const handleNext = async () => {

    

    const fields=  form.getFieldValue("latestMaintenanceTime");
    if(fields!=undefined){
      setBtnDisabled(true);
    }
   
    const fieldsValue = await form.validateFields();
   
  
    if (fieldsValue.onlineTime) {
      fieldsValue.onlineTime = fieldsValue.onlineTime.format('YYYY-MM-DD HH:mm:ss');
    }
    if (fieldsValue.latestMaintenanceTime) {
      fieldsValue.latestMaintenanceTime = fieldsValue.latestMaintenanceTime.format('YYYY-MM-DD HH:mm:ss');
    }
    // Object.assign(formValues, fieldsValue);
    let configs = new Map();
    if (fieldsValue.sights) {
      fieldsValue.sights.map((item) => {
        if(configItem.indexOf(item.key)==-1)
          configs.set(item.key,item.value);
      })
      let config= JSON.stringify([...configs]);
      console.log(config);
      config=config.replaceAll("[[","{").replaceAll("]]","}").replaceAll("\",\"","\":\"").replaceAll("],[",",");
      console.log(config)
      let config1= JSON.stringify(strMapToObj(configs));
      console.log(config1);
      fieldsValue.protocolConfig = config;
    }
 
    setFormValues({...formValues,...fieldsValue});
    if (currentStep < 2) {
      forward();
    } else {
      try {
        await addDevice({...formValues,...fieldsValue});
        goBack();
      } catch (error) {
        setBtnDisabled(false);
        message.error('添加失败请重试！');
  
      }
    }
  };

   let strMapToObj=(strMap)=>{
    let obj= Object.create(null);
    for (let[k,v] of strMap) {
        obj[k] = v;
    }
    return obj;
}


  const goBack =  () => {
    setFormValues({});
    form.resetFields();
    setCurrentStep(0);
    history.goBack();

  };

  useEffect(() => {
    var  deviceTypes =JSON.parse(localStorage.getItem("deviceTypeList")||"[]");
    var  drivers =JSON.parse(localStorage.getItem("driverList")||"[]");
    var  areas=JSON.parse( localStorage.getItem("areaTree")||"[]");
    if(dicts){
      setProtocolTypeList(dicts[2]);
    }
    setDeviceTypeList(deviceTypes);
    setDriverList(drivers);
    setAreaTree(areas);
  }, [])





  const changeDriver = (e,e1) =>{
  
    var sights=[];
    var driver= driverList[e1.key];
    if(driver.driverType==1){
      sights.push({value: driver.commandPort, key: 'commandPort'});
      sights.push({value: driver.dataBits, key: 'dataBits'});
      sights.push({value: driver.baudRate, key: 'baudRate'});
      sights.push({value: driver.stopBits, key: 'stopBits'});
      sights.push({value: driver.stopBits, key: 'parity'});
      sights.push({value: '', key: 'slaveId'});
      setConfigRow(6);
    }else{
      sights.push({value: driver.ipport, key: 'ipport'});
      setConfigRow(1);
    }
      form.setFieldsValue({sights}   );
    
  }
  
  
  const renderFooter = () => {
    if (currentStep === 1) {
      return (
        <>
          <Button  onClick={backward}>
            上一步
          </Button>
          <Button onClick={() =>goBack()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            下一步
          </Button>
        </>
      );
    }
    if (currentStep === 2) {
      return (
        <>
          <Button  onClick={backward}>
            上一步
          </Button>
          <Button onClick={() =>{  goBack()}  }>取消</Button>
          <Button type="primary" disabled={btnDisabled} onClick={() => {  handleNext()}}>
            完成
          </Button>
        </>
      );
    }
    return (
      <>
        <Button onClick={() => goBack()}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>
          下一步
        </Button>
      </>
    );
  };

  const renderContent = () => {
    if (currentStep === 0) {
      return (
        <>
           <FormItem
          label="设备名称"
          name="deviceName"
          rules={[{ required: true, message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="设备位号"
          name="deviceNo"
          rules={[{ required: true, message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
            label="所在区域"
            name="areaId"
            rules={[{ required: true, message: '请选择所在区域' }]}
          >
             <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={areaTree}
            
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          />
          </FormItem>
          <FormItem
            label="设备类型"
            name="deviceTypeId"
            rules={[{ required: true, message: '请选择设备类型' }]}
          >
            <Select placeholder="请选择设备类型">
            {deviceTypeList.map((item) => (
              <Option key={item.typeId} value={item.typeId}>
                {item.typeName}
              </Option>
           ))}
            </Select>
          </FormItem>
          <FormItem
            label="设备驱动"
            name="driverId"
            rules={[{ required: true, message: '请选择设备驱动' }]}
          >
            <Select placeholder="请选择设备驱动"  onChange={(e,e1)=>changeDriver(e,e1)}>
            {driverList.map((item,index) => (
              <Option key={index} value={item.id}>
                {item.name}
              </Option>
           ))}
            </Select>
          </FormItem>
          <FormItem
            label="通讯协议类别"
            name="protocolType"
            rules={[{ required: true, message: '请选择通讯协议类别' }]}
          >
            <Select placeholder="请选择通讯协议类别" >
         
             {protocolTypeList.map((item,index) => (
              <Option key={item.dictCode} value={item.dictCode}>
                {item.dictValue} 
              </Option>
           ))}
            </Select>
          </FormItem>
         
        
          <FormItem
            label="通讯协议配置"
         
          >
          <Form.List name="sights">
            {(fields, { add, remove }) => (
              <>
                {fields.map(field => (
                  <Space style={{ display: 'flex', marginBottom: 8 }}  className={ styles.sightsSpace}   key={field.key} align="baseline">
                    
                    <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{ flex:1}}
                      name={[field.name, 'key']}
                      fieldKey={[field.fieldKey, 'key']}
                      rules={[{ required: true, message: '请输入配置名' }]}
                    >
                     { field.fieldKey< configRow&& field.fieldKey<5? <Input placeholder="请输入配置名" disabled  />:  <Input placeholder="请输入配置名" />} 
                    </Form.Item>
                    {field.name ==5&& configRow==6? <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{ flex:1}}
                      name={[field.name, 'value']}
                      fieldKey={[field.fieldKey, 'value']}
                      rules={[{ required: true, message: '请输入配置值' }]}
                    >
                       <Input  placeholder="请输入配置值"/>
                    </Form.Item>:  
                      <Form.Item
                        {...field}
                        {...formItemLayout}
                        style={{ flex:1}}
                        name={[field.name, 'value']}
                        fieldKey={[field.fieldKey, 'value']}
                        rules={[{ required: true, message: '请输入配置值' }]}
                        
                      >
                         { field.fieldKey< configRow? <Input placeholder="请输入配置值" disabled  />:  <Input placeholder="请输入配置值" />}  
                      </Form.Item> }   
                    {field.fieldKey>=configRow?
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                    :<></>
                    }
                  
                  </Space>
                ))}
               
               
                    <Button  type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加配置
                    </Button>
             
                
              </>
            )}
          </Form.List>
          </FormItem>
        </>
      );
    }
    if (currentStep === 1) {
      return (
        <>
            <FormItem
          label="设备位置"
          name="devicePosition"
          rules={[{ required: true, max: 100, min: 2}]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
       
          <FormItem
          label="设备描述"
          name="deviceDesc"
          // rules={[{ required: true, message: '请输入至少十个字符！', min: 10,max:255 }]}
          rules={[{ min: 5,max:255 }]}
        
        >
          <TextArea  placeholder="请输入" showCount maxLength={255}  />
        </FormItem>
       
        <FormItem
          label="启用状态"
          name="useState"
        >
          <Radio.Group >
            <Radio value={0} >
              不启用
            </Radio>
            <Radio value={1}>
              启用
            </Radio>
          </Radio.Group>
        </FormItem>
          <FormItem
          label="设备品牌"
          name="deviceBrand"
          rules={[{max: 50, min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="设备型号"
          name="deviceModel"
          rules={[{  max: 50, min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="产品序列号"
          name="seriaNumber"
          rules={[{  max: 50, min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
      
        <FormItem
            label="上线时间"
            name="onlineTime"
            rules={[]}
          >
            <DatePicker  format="YYYY-MM-DD HH:mm:ss"   showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} placeholder='请选择上线时间' style={{ width: '100%' }} />
          </FormItem>
        
        </>);
    }

    
    return (
      <>
       <FormItem
            label="最新维保时间"
            name="latestMaintenanceTime"
            rules={[{ required: true}]}
          >
            <DatePicker  format="YYYY-MM-DD HH:mm:ss"   showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} placeholder='请选择上线时间' style={{ width: '100%' }} />
          </FormItem>
          <FormItem
          label="供货商"
          name="supplier"
          rules={[{ max: 50, min: 2 }]}
          >
            <Input placeholder="请输入"  />
          </FormItem>
          <FormItem
          label="供货商联系人姓名"
          name="supplierName"
          rules={[{ max: 50, min: 2 }]}
          >
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem
          label="供货商联系人电话"
          name="supplierPhone"
          rules={[{ validator: validatorMobile}]}
          >
            <Input placeholder="请输入"   />
          </FormItem>
      </>
    );
  }

  return (
    <div className={styles.main}>
      <a   onClick={()=>goBack()}> 返回上一级  </a>
      <Card>
        <Steps style={{ marginBottom: 28 }} current={currentStep}>
            <Step title="基本信息1" />
            <Step title="基本信息2" />
            <Step title="基本信息3" />
          </Steps>
      
          <Form
            {...formLayout}
            form={form}
            initialValues={formValues}
          >
            {renderContent()}
          </Form>
          <div className={styles.formFooter}>{renderFooter()}</div>
          </Card>
      </div>
       
  );
};

export default CreatDevice;